import dd from 'gdt-jsapi';
import api from '../../api/index'
import utils, {formatTs} from '../../common/utils'
import {getUserInfo} from '../../common/common'

Page({
  data: {
    userInfo: {},
    ApplyStatus: {
      Pending: 1,
      Passed: 2,
      Rejected: 3,
      Canceled: 4,
    },
    ApproveStatus: {
      Passed: 1,
      Rejected: 2,
    },
    TabsType: {
      Pending: 1,
      Approved: 2,
    },
    applyTabIndex: 1,
    applyList: [],
    approveApplyList: [],
    personCacheObj: {},
    currentApply: {},
    approveModalVisible: false,
    approveLoading: false,
    approvePass: true,
    approveRemark: '',
  },
  async getPersonList() {
    try {
      const res = await api.getPersonList()
      if (res.data && res.data.length) {
        res.data.forEach((p) => {
          this.data.personCacheObj[p.accountId] = p
        })
      }
    } catch(e){

    }
  },

  async onLoad(options) {
    const tab = options.tab
    const id = options.id
    const status = options.status// 1  2
    await this.getPersonList()
    this.data.userInfo = await getUserInfo()
    //this.data.userInfo = {accountId: '8825254'}
    if (tab) {
      this.onApplyTabClick(null, Number(tab))
    } else {
      this.getPendingMyApproveApplyList()
    }
    if (id && status) {
      const apply = await this.getApplyDetail(id)
      if (apply) {
        this.onApprove(null, {
          item: apply.detail,
          status: Number(status) === this.data.ApproveStatus.Passed ? true : false,
        })
      }
    }
  },
  async getApplyDetail(id){
    try {
      const res = await api.getApplyDetail(id)
      if (res.data) {
        return res.data
      }
    } catch(e){
      return null
    }
  },
  async getDevicePlanObj (deviceSn) {
    let res = null
    try {
      res = await api.getDevicePlan(deviceSn)
    } catch(e){}
    return res
  },
  /**
   * 获取待我审批的列表
   */
  async getPendingMyApproveApplyList(){
    dd.showLoading({
      text: '加载中'
    })
    if (!this.data.userInfo.accountId) {
      this.data.userInfo = await getUserInfo()
    }
    api.getPendingMyApproveApplyList(this.data.userInfo.accountId).then((res) => {
      if (res.data && res.data.length) {
        res.data.forEach((apply) => {
          apply.approveList = []
          apply.applyTimeStr = formatTs(Number(apply.applyTime))
          apply.approvePersonNames = ''
          if (apply.approveAccountIdList) {
            const approve = []
            const approveArr = apply.approveAccountIdList.split(',')
            approveArr.forEach((id) => {
              if (id && this.data.personCacheObj[id]) {
                approve.push(this.data.personCacheObj[id].name)
              }
            })
            apply.approvePersonNames = approve.join('，')
          }
        })
        this.setData({
          applyList: res.data,
        })
      }
      dd.hideLoading()
    }).catch((e) => {
      dd.hideLoading()
    })
  },
  /**
   * 获取我的审批列表
   * @returns {Promise<void>}
   */
  async getMyApproveApplyList(){
    dd.showLoading({
      text: '加载中'
    })
    if (!this.data.userInfo.accountId) {
      this.data.userInfo = await getUserInfo()
    }
    api.getMyApproveList(this.data.userInfo.accountId).then((res) => {
      if (res.data && res.data.length) {
        res.data.forEach((approve) => {
          approve.approveTimeStr = formatTs(Number(approve.approveTime))
          approve.applyInfo.applyTimeStr = formatTs(Number(approve.applyInfo.applyTime))
          approve.applyInfo.approvePersonNames = ''
          if (approve.applyInfo.approveAccountIdList) {
            const approveNames = []
            const approveArr = approve.applyInfo.approveAccountIdList.split(',')
            approveArr.forEach((id) => {
              if (id && this.data.personCacheObj[id]) {
                approveNames.push(this.data.personCacheObj[id].name)
              }
            })
            approve.applyInfo.approvePersonNames = approveNames.join('，')
          }
        })
        this.setData({
          approveApplyList: res.data,
        })
      }
      dd.hideLoading()
    }).catch((e) => {
      console.log(e)
      dd.hideLoading()
    })
  },
  onApplyTabClick(e, i){
    let index = i
    if (e) {
      index = Number(e.target.dataset.type)
    }
    this.setData({
      applyList: [],
      approveApplyList: [],
      applyTabIndex: index
    })
    if (index === this.data.TabsType.Pending) {
      this.getPendingMyApproveApplyList()
    }
    if (index === this.data.TabsType.Approved) {
      this.getMyApproveApplyList()
    }
  },
  bindApproveRemarkInput(e){
    this.setData({
      approveRemark: e.detail.value
    })
  },
  onSwitchChange(e){
    this.data.approvePass = e.detail.value
    this.setData({
      approvePass: e.detail.value,
    })
  },
  async onViewDetail(e){
    dd.showLoading({
      text: '加载中'
    })
    const index = Number(e.target.dataset.index)
    const item = this.data.applyList[index]
    const data = await this.getApplyDetail(item.id)
    dd.hideLoading()
    if (data && data.approveList.length) {
      data.approveList.forEach((approve) => {
        approve.approveTimeStr = formatTs(Number(approve.approveTime))
      })
      item.approveList = data.approveList
      this.setData({
        ['applyList['+index+']']: item
      })
    } else {
      dd.showToast({
        content: '暂无审批记录',
        type: 'none'
      })
    }
  },
  onApprove(e, data){
    let item
    if (data) {
      item = data.item
      this.data.approvePass = data.status
    }
    if (e) {
      item = e.target.dataset.item
      this.data.approvePass = true
    }
    this.data.approveRemark = ''
    console.log(e, data, item)
    this.setData({
      approvePass: this.data.approvePass,
      currentApply: item,
      approveModalVisible: true
    })
  },
  onCancelApprove(){
    this.setData({
      approveModalVisible: false
    })
  },
  executeApproveSubmit(){
    dd.showLoading({
      text: '加载中'
    })
    const data = {
      id: '',
      applyId: this.data.currentApply.id,
      deviceSn: this.data.currentApply.deviceSn,
      applyAccountId: this.data.currentApply.applyAccountId,
      approveAccountId: this.data.userInfo.accountId,
      approveTime: '',
      approveRemark: this.data.approveRemark,
      status: this.data.approvePass ? this.data.ApproveStatus.Passed : this.data.ApproveStatus.Rejected,
    }
    api.approve(data).then((res) => {
      dd.hideLoading()
      if (res.code === 0) {
        dd.showToast({
          content: '审批成功',
          type: 'success'
        })
        this.setData({
          approveModalVisible: false
        })
        this.getPendingMyApproveApplyList()
      } else {
        dd.showToast({
          content: res.message || '审批失败',
          type: 'fail'
        })
      }
    }).catch((e) => {
      dd.hideLoading()
      dd.showToast({
        content: '服务异常',
        type: 'exception'
      })
    })
  },
  async onSubmitApprove(){
    const devicePlan = await this.getDevicePlanObj(this.data.currentApply.deviceSn)
    let intersectionArr = []
    if (devicePlan && devicePlan[this.data.currentApply.applyUseDate]) {
      const applyUseTimeRangeArr = this.data.currentApply.applyUseTimeRange.split('-')
      intersectionArr = utils.judgeCanUse(applyUseTimeRangeArr[0], applyUseTimeRangeArr[1], devicePlan[this.data.currentApply.applyUseDate])
    }
    if (intersectionArr.length) {
      dd.confirm({
        title: "温馨提示",
        message: `申请的使用时段与已存在的【${intersectionArr.join(',')}】时段有冲突，确定继续吗?`,
        buttonLabels: [
          "确定",
          "取消"
        ],
      }).then(res => {
        if (res.buttonIndex === 0) {
          this.executeApproveSubmit()
        }
      }).catch(err => {})
    } else {
      this.executeApproveSubmit()
    }
  },
});
